/*
	后台-图片控制器
*/
'use strict';
var moment		= require('moment');
var AV 				= require('leanengine');
var mdCommon	= require('../modules/common');

var avReport 		= AV.Object.extend("ReportLog");

/**
 * 用户列表页面
 * 2015.04.18  by 胡斌
 */
exports.listPage = function(req, res) {
	var pager,where	= " objectId is exists",urlParam="",param={};
	var param1			= ["objectId"];
	var param2			= ["enabled"];
	var search			= req.query.search;
	
	param['type']=req.query.type?req.query.type:"comment";
	where	+= " and type='"+param['type']+"'";
	urlParam+="&type="+param['type'];
	
	param['state']=parseInt(req.query.state?req.query.state:"0");
	where	+= " and state="+param['state'];
	urlParam+="&state="+param['state'];
	//console.log('select count(*) from _User where'+where);
	AV.Query.doCloudQuery('select count(*) from ReportLog where'+where).then(function(data){
		pager		= mdCommon.Paginate(req.query.page, req.query.pagesize, data.count);
		return AV.Query.doCloudQuery('select include '+param['type']+',include user,* from ReportLog where'+where+' limit '+(pager.currentPage-1)*pager.pagesize+','+pager.pagesize);
	}).then(function(data) {
		res.render('admin-report-list.html',{
			user:req.AV.user,
			results:data.results,
			moment:moment,
			pager:pager,
			urlParam:urlParam,
			param:param
		});
	},function(error) {
		mdCommon.sentErr(res,req,error);
	});
}

/**
 * 删除图片
 * 2015.05.02  by 胡斌
 */
exports.doDelete = function(req, res) {
	var ids					= req.body.ids;
	var queryComment 	= new AV.Query(avComment);
	if(typeof(ids)=="undefined")ids="-1";
	var idArr				= ids.split(",");

	queryComment.containedIn("objectId",idArr);
	queryComment.destroyAll().then(function(results) {
		if(req.body.ajax){
			res.json({success:true});
		}else{
			res.redirect('/admin/report/list');
		}
  },function(error) {
		mdCommon.sentErr(res,req,error);
	});
}

exports.doSet = function(req, res) {
	var ids					= req.body.ids;
	var queryComment 	= new AV.Query(avComment);
	if(typeof(ids)=="undefined")ids="-1";
	var idArr				= ids.split(",");
	var type				= req.body.type;

	queryComment.containedIn("objectId",idArr);
	queryComment.find().then(function(results){
		var enabled;
		if(type=="open"){
			enabled=true;//
		}else if(type=="ban"){
			enabled=false;//
		}
		if(typeof(enabled)=="boolean"){
			var promises = [];
			for(var i=0;i<results.length;i++){
				results[i].set("enabled",enabled);
				promises.push(results[i].save());
			}
			return AV.Promise.when(promises);
		}else{
			return AV.Promise.error('错误的指令！');//
		}
	}).then(function(results) {
		if(req.body.ajax){
			res.json({success:true});
		}else{
			res.redirect('/admin/report/list');
		}
  },function(error) {
		mdCommon.sentErr(res,req,error);
	});
}
